package service;

import common.Message;
import common.MessageType;
import utils.Utility;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;
import java.util.List;

/**
 * @Description: 推送消息类
 * @CreateTime: 2024-02-27  14:59
 * @Author: JAMILA
 * @Version: 1.0
 */

public class SendNewsToAllService implements Runnable {

    @Override
    public void run() {
        while (true){
            System.out.print("请输入服务端要推送的新闻/消息[输入exit可退出推送服务]：");
            String news = Utility.readString(1000);
            if ("exit".equals(news)) {
                System.out.println("服务端退出推送服务");
                break;
            }
            Message message = new Message();
            message.setMesType(MessageType.MESSAGE_TO_ALL_MES);
            message.setSender("服务端");
            message.setSendTime(new Date().toString());
            message.setContent(news);
            System.out.println("服务器推送给所有人说："+news);

            List<ServerConnectClientThread> allServerConnectClientThread = ManageClientThreads.getAllServerConnectClientThread(message.getSender());
            for (ServerConnectClientThread thread : allServerConnectClientThread) {
                try {
                    ObjectOutputStream oos = new ObjectOutputStream(thread.getSocket().getOutputStream());
                    oos.writeObject(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }

    }
}
